package at.mri.dogwatch.client.pages.newestfeed;

import at.mri.dogwatch.client.place.NameTokens;
import at.mri.dogwatch.shared.proxy.VideoProxy;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.NoSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewImpl;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;

public class NewVideosFeedView extends ViewImpl implements
		NewVideosFeedPresenter.MyView {

	private final Widget widget;
	
	@UiField(provided = true) CellList<VideoProxy> lastVideosList;
	@UiField SimplePager lastVideosPager;
	
	@Inject PlaceManager placeManager;

	private NoSelectionModel<VideoProxy> selectionModel;

	private final AsyncDataProvider<VideoProxy> dataProvider;
	
	
	
	public interface Binder extends UiBinder<Widget, NewVideosFeedView> {
	}

	@Inject
	public NewVideosFeedView(final Binder binder, AsyncDataProvider<VideoProxy> dataProvider) {
		this.dataProvider = dataProvider;
		lastVideosList = new CellList<VideoProxy>(new VideoProxyCell());
		
		widget = binder.createAndBindUi(this);
		lastVideosList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.DISABLED);
		
		selectionModel = new NoSelectionModel<VideoProxy>();
		lastVideosList.setSelectionModel(selectionModel);
		
		dataProvider.addDataDisplay(lastVideosList);
		lastVideosPager.setDisplay(lastVideosList);

		
		
		selectionModel.addSelectionChangeHandler(new Handler() {
			
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				VideoProxy proxy = selectionModel.getLastSelectedObject();
				//navigate to this 
				
				PlaceRequest request = new PlaceRequest(NameTokens.videodetails);
				placeManager.revealPlace(request.with(NameTokens.VIDEO_ID_PARAM, proxy.getId().toString()), true);
			}
		});
	}
	
	
	
	@Override
	public void addVideoSelectionChangeHandler(Handler handler){
		selectionModel.addSelectionChangeHandler(handler);
	}
	
	public void refreshVideoFeed(){
		lastVideosList.setVisibleRangeAndClearData(lastVideosList.getVisibleRange(), true);
	}

	@Override
	public Widget asWidget() {
		return widget;
	}
	
	
}
